/**
 * Created by billy on 2020/12/21.
 */
global.__system_cmd = false;
var pathObj = g.path.parse(__filename);
var packagePath = g.path.join(pathObj.dir, "./package.json");
while (!g.fs.existsSync(packagePath))
{
	pathObj = g.path.parse(pathObj.dir);
	packagePath = g.path.join(pathObj.dir, "./package.json");
}

global._path = function (...arg)
{
	return g.path.join(pathObj.dir, ...arg);
};

global._bin = function ($path = "")
{
	if ($path)
	{
		$path.indexOf(".js") < 0 && ($path += ".js");
		let binFilePathObj = g.path.parse($path);
		if (binFilePathObj.base.substr(0, 4) != "bin_")
		{
			$path = binFilePathObj.dir + "/bin_" + binFilePathObj.base;
		}
	}
	return _path("./bin", $path);
};

global.__time = require("./time");
global.__argv = require("./argv");
global.__op = require("./operation");

var _ossHash = {};
global._ossClient = function ($bucket)
{
	$bucket = "tingjun-" + $bucket;
	if (_ossHash[$bucket])
	{
		return _ossHash[$bucket];
	}
	var OssClient = require("ali-oss");
	_ossHash[$bucket] = new OssClient({
		bucket: $bucket,
		...g.data.conf.oss
	});
	return _ossHash[$bucket];
}

global._log = require("./log");

global.trace = function ()
{
	var arr = [`【${__argv.name}】`];
	for (var i = 0; i < arguments.length; i++)
	{
		arr.push(arguments[i]);
	}
	console.log.apply(console.log, arr);
}

global.__exit = function (...arg)
{
	if (arg.length > 0)
	{
		log.success("【Success】" + arg.join(" ") + " " + __time);
	}
	else
	{
		log.success("【Success】Done ~~ " + __time);
	}
	for (var logFile of _log.logFile)
	{
		log.success("【log】" + logFile)
	}
	exit();
}

global.__exit.error = function (...arg)
{
	if (arg.length > 0)
	{
		log.error("【Error】" + arg.join(" "));
	}
	exit();
}

global.__setTimeout = function (callback, time)
{
	return _promise(r=>
	{
		setTimeout(()=>
		{
			callback();
			r();
		}, time)
	})
}

var _mysqlHash = {
	dev: "listen-dev-ver2-0",
	test: "listen-test-ver2-0",
	release: "listen-ver2-0"
};
global._mysqlClient = function ($db)
{
//	listen-test-ver2-0
	if (_mysqlHash[$db])
	{
		if (typeof _mysqlHash[$db] == "string")
		{
			var dbName = _mysqlHash[$db];
			_mysqlHash[$db] = g.mysql_server.create({
				...g.data.conf.mysql,
				database: dbName
			});
		}
		return _mysqlHash[$db];
	}
	return null;
}